<template>
    <div class="page-container">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="文件夹权限列表" name="config" v-if="showConfig">
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button
                                type="primary"
                                plain
                                icon="el-icon-plus"
                                size="mini"
                                @click="handleAddDir"
                            >AddFileDir
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-table
                        :data="filesConfigList"
                        style="width: 100%">
                        <el-table-column
                            prop="menuName"
                            label="文件夹名称"
                            width="180">
                        </el-table-column>
                        <el-table-column
                            prop="perms"
                            label="权限">
                        </el-table-column>
                        <el-table-column label="Operate" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.row)"
                                    v-hasPermi="['business:goodCatch:remove']"
                                >Delete
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            <el-tab-pane v-for="(item,index) in treeData" :label="item.label" :name="'pane'+index" :key="'pane'+index">
                <el-form size="small" :inline="true" @submit.native.prevent>
                    <el-form-item label="Input" prop="roleName">
                        <el-input
                            v-model="searchValue"
                            placeholder="Input"
                            clearable
                            style="width: 240px"
                            @keyup.enter.native="handleQuery(item.label)"
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery(item.label)">
                            Search
                        </el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="handleReset">Reset</el-button>
                    </el-form-item>
                </el-form>
                <el-table v-if="item.children.length > 0"
                          :data="item.children"
                          style="width: 100%;margin-bottom: 20px;"
                          row-key="filePath"
                          border
                          default-expand-all
                          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                    <el-table-column
                        prop="label"
                        label="文件夹"
                        sortable
                        width="auto">
                    </el-table-column>
                    <el-table-column
                        prop="Operate"
                        label="操作">
                        <template slot-scope="scope">
                            <el-row>
<!--                                <el-col :span="2">
                                    <el-button
                                        v-if="scope.row.isFile"
                                        type="text"
                                        size="mini"
                                        @click="() => downloadFile(scope.row)">
                                        下载
                                    </el-button>
                                </el-col>-->
                                <el-col :span="2">
                                    <el-button
                                        v-if="scope.row.isFile && scope.row.label.endsWith('.pdf')"
                                        type="text"
                                        size="mini"
                                        @click="() => viewPdf(scope.row)"
                                    > 预览
                                    </el-button>
                                </el-col>
<!--                                <el-col :span="4">-->
<!--                                    <el-switch-->
<!--                                        v-if="scope.row.isFile && scope.row.label.endsWith('.pdf')"-->
<!--                                        v-model="scope.row.readStatus"-->
<!--                                        :disabled="getViewState(scope.row.filePath)"-->
<!--                                        @change="viewChange(scope.row.readStatus,scope.row.filePath)"-->
<!--                                        active-text="是"-->
<!--                                        inactive-text="否">-->
<!--                                    </el-switch>-->
<!--                                </el-col>-->
                                <el-col :span="8">
                                    {{scope.row.readTime }}
                                </el-col>
                            </el-row>
                        </template>
                    </el-table-column>

                </el-table>
            </el-tab-pane>
        </el-tabs>
        <!-- 添加或修改goodCatch对话框 -->
        <el-dialog title="增加文件夹" :visible.sync="open" width="50%" :append-to-body="true"
                   :close-on-click-modal="false">
            <el-form ref="form" :model="newFileForm" label-width="auto">
                <el-form-item label="文件夹名称" prop="menuName">
                    <el-input v-model="newFileForm.menuName" placeholder="Input FileDirName"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">Submit</el-button>
                <el-button @click="cancel">Cancel</el-button>
            </div>
        </el-dialog>
        </el-tabs>
    </div>
</template>
<style>
.page-container {
    margin-left: 20px; /* 调整这个值以实现您想要的右移效果 */
}
</style>
<script>
import {addFirstConfig, deleteFirstConfig, getFirstConfig, listPath} from "@/api/business/first-origin";
import {addVerb, listVerb,listVerbAll, updateVerb, updateVerbStatus} from "@/api/business/verb";
import {download, downloadBlob} from "@/utils/request";
import {parseTime} from "@/utils/ruoyi";

export default {
    data() {
        return {
            searchValue: "",
            originTreeData: [],
            showConfig: false,
            newFileForm: {
                menuName: '',
                perms: ''
            },
            open: false,
            filesConfigList: [],
            activeName: '',
            treeData: [],
            subTreeData: [],
            pdfList: [], // 存储PDF文件信息的数组
            pdfUrl: '',
            viewFileData: []
        };
    },
    components: {},
    methods: {
        parseTime,
        handleFilter(item, searchValue) {
            let newChildren = []
            // 递归遍历本文件夹下的子文件夹
            let children = item.children
            if (children.length > 0) {
                for (let i = 0; i < children.length; i++) {
                    const oldChildren = children[i]
                    // 如果有符合的加入
                    let newChildrenItem = this.handleFilter(oldChildren, searchValue)
                    if (newChildrenItem !== null) {
                        newChildren.push(newChildrenItem)
                    }
                }
            }
            // 处理当前文件夹下的文件
            let label = item.label
            // 如果搜索的值中包含字母转化成大写
            let searchValueCopy = '';
            for (let i = 0; i < searchValue.length; i++) {
                if (/^[a-zA-Z]*$/.test(searchValue.charAt(i))) {
                    searchValueCopy += searchValue.charAt(i).toUpperCase()
                } else {
                    searchValueCopy += searchValue.charAt(i)
                }
            }
            // 找到最后的文件名
            let fileNameCopy = label
            let newFileName = ''
            fileNameCopy = fileNameCopy.replace(".pdf", "");
            // 如果文件名的值中包含字母转化成大写
            for (let i = 0; i < fileNameCopy.length; i++) {
                if (/^[a-zA-Z]*$/.test(fileNameCopy.charAt(i))) {
                    newFileName += fileNameCopy.charAt(i).toUpperCase()
                } else {
                    newFileName += fileNameCopy.charAt(i)
                }
            }
            item.children = newChildren
            // 如果当前字段不包含搜索  但是 子文件包含 或者当前字段包含搜索，且没有子文件，则返回当前节点
            if (newFileName.indexOf(searchValueCopy.toUpperCase()) < 0 && newChildren.length > 0 ||
                newFileName.indexOf(searchValueCopy.toUpperCase()) > -1 && newChildren.length === 0) {
                return item
            } else {
                return null
            }
        },
        handleQuery(label) {
            let data = JSON.parse(JSON.stringify(this.originTreeData))
            let newData = []
            for (let i = 0; i < data.length; i++) {
                // 判断当前的tab
                if (data[i].label === label) {
                    const oldItem = data[i]
                    const newItem = this.handleFilter(oldItem, this.searchValue)
                    if (null !== newItem) {
                        newData.push(newItem)
                    } else {
                        oldItem.children = []
                        newData.push(oldItem)
                    }
                } else {
                    newData.push(data[i])
                }

            }
            if (newData.length < 1) {
                this.$message.warning("No file contain")
                this.treeData = JSON.parse(JSON.stringify(this.treeData))
            } else {
                this.treeData = JSON.parse(JSON.stringify(newData))
            }
        },
        handleReset() {
            this.searchValue = ''
            this.treeData = JSON.parse(JSON.stringify(this.originTreeData))
        },
        handleClick(tab, event) {
            this.searchValue = ''
        },
        downloadFile(node) {
            const data = {
                employeeId: this.$store.getters.employeeId,
                name: this.$store.getters.name,
                deptId: this.$store.getters.deptId,
                fileName: node.filePath,
                readStatus: "o"
            }
            addVerb(data).then(res => {
                download("/common/downloadAny", {'fileName': node.filePath}, node.label)
                this.loadPdfList();
            })
        },
        async getViewFileData() {
            const data = {
                employeeId: this.$store.getters.employeeId
            }
            await listVerbAll(data).then(res => {
                console.log(res)
                this.viewFileData = res.data;
            })
        },
        getViewState(filePath) {
            const data = this.viewFileData.find(item => item.filePath === filePath)
            return !(data && data.readStatus === 'o');
        },
        getViewStateHasRead(filePath) {
            const data = this.viewFileData.find(item => item.filePath === filePath)
            return data && data.readStatus === 'y';
        },
        getViewData(filePath) {
            // 过滤和文件名一样的记录
            const files =  this.viewFileData.filter(item =>{return filePath === item.filePath; });
            return files.length > 0 ? files[0] : null;
        },
        containFilePath(filePath) {
            const data = this.viewFileData.map(item => {
                return item.filePath
            })
            return data.indexOf(filePath) > -1;
        },
        viewChange(val, node) {
            if (val) {
                const data = {
                    employeeId: this.$store.getters.employeeId,
                    filePath: node,
                    readStatus: "y",
                }
                updateVerbStatus(data).then(res => {
                    this.loadPdfList();
                })
            }
        },
        viewPdf(node) {
            const data = {
                employeeId: this.$store.getters.employeeId,
                name: this.$store.getters.name,
                deptId: this.$store.state.user.deptId,
                fileName: node.filePath,
                readStatus: "o"
            }
            addVerb(data).then(res => {
                downloadBlob("/common/downloadAny", {'fileName': node.filePath}, node.label).then(res => {
                    const binaryData = [];
                    binaryData.push(res);
                    //获取blob链接
                    this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
                    window.open(this.pdfUrl);
                    window.URL.revokeObjectURL(this.pdfUrl);
                })
                this.loadPdfList();
            })
        },
        loadPdfList() {
            this.getViewFileData().then(res => {
                listPath("D:\\nsk-sbv3\\uploadPath",this.searchValue).then((res) => {
                    const resData = res.data
                    let root = [{
                        /*readStatus: false,*/
                        isFile: false,
                        id: 1,
                        label: "一级文件",
                        filePath: "D:\\nsk-sbv3\\uploadPath",
                        children: []
                    }]
                    // 增加配置面板
                    this.treeData = this.parseData(resData);
                    root[0].children = this.treeData
                    this.treeData = root
                    this.originTreeData = root
                    this.activeName = 'pane0'
                })
            });
        },
        parseData(data, beginId) {
            if (beginId === undefined || beginId < 0) {
                beginId = 0;
            }
            let res = [];
            const dirs = data.dir;
            if (dirs && dirs.length > 0) {
                for (const dir of dirs) {
                    let fileName = dir.path.split("\\");
                    let arr = this.parseData(dir, ++beginId)
                    res.push({
                        readStatus: false,
                        readTime: null,
                        isFile: false,
                        id: ++beginId,
                        label: fileName[fileName.length - 1],
                        filePath: dir.path,
                        children: arr,
                        hasChildren: arr > 0
                    })
                }
            }
            const files = data.files
            if (files && files.length > 0) {
                for (const file of files) {
                    if (!file.endsWith("pdf")) {
                        continue
                    }
                    let fileName = file.split("\\");
                    const viewData = this.getViewData(file)
                    console.log(viewData)
                    let contain = false;
                    let readTime = null;
                    if (viewData) {
                        contain =  viewData.readStatus === 'y';
                        readTime = parseTime(viewData.firstTime)
                    }
                    res.push({
                        readStatus: contain,
                        readTime: readTime,
                        isFile: true,
                        id: ++beginId,
                        label: fileName[fileName.length - 1],
                        filePath: file,
                        children: []
                    })
                }
            }
            return res;
        },
        listFirstConfig() {
            getFirstConfig().then(res => {
                this.filesConfigList = res.data;
                console.log(this.filesConfigList)
            })
        },
        handleAddDir() {
            this.newFileForm = {};
            this.open = true;
        },
        handleDelete(row) {
            const id = row.menuId;
            this.$modal.confirm('Delete FileDir？').then(function () {
                return deleteFirstConfig(id);
            }).then(() => {
                this.listFirstConfig();
                this.$modal.msgSuccess("Delete Success");
            }).catch(() => {
            });
        },
        /** 提交按钮 */
        submitForm() {
            console.log(this.newFileForm.menuName)
            if (undefined === this.newFileForm.menuName || null === this.newFileForm.menuName || this.newFileForm.menuName === '') {
                this.$message({
                    message: '请输入文件夹名称',
                    type: 'error'
                });
                return;
            }
            addFirstConfig(this.newFileForm.menuName).then(res => {
                this.open = false;
                this.$modal.msgSuccess("Add Success");
                this.listFirstConfig();
            })
        },
        cancel() {
            this.open = false;
        },
    },
    created() {
        // 如果有权限则请求文件夹权限列表
        if (this.$auth.hasPermi("business:first:config")) {
            this.listFirstConfig();
            this.showConfig = true;
        }
        this.loadPdfList();
    }
};

</script>
